<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <hr />
    <div class="add-book">
      <h2>添加书本</h2>
      <div class="book-name">
        书本名称:
        <input type="text" id="name" ref="name" />
      </div>
      <div class="book-price">
        书本价格:
        <input type="text" id="price" ref="price" />
      </div>
      <div>
        <button @click="addToBookList">添加到书本列表</button>
      </div>
      <hr />
    </div>
    <div class="book-list">
      <h2>书本列表</h2>
      <table>
        <tr>
          <th>书本名称</th>
          <th>书本价格</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) of bookList" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="addBookToCar(index)">添加到购物车</button>
          </td>
        </tr>
      </table>
      <hr />
    </div>
    <car :bookItem="bookItem" @add="add" @minus="minus" />
  </div>
</template>

<script>
import Car from "@/components/Car";
export default {
  components: {
    Car
  },
  data() {
    return {
      title: "book shop",
      book: {
        id: null,
        name: "",
        price: null
      },
      bookList: [
        {
          id: 1,
          name: "老人与海",
          price: 9.9
        },
        {
          id: 2,
          name: "JavaScript高级程序设计",
          price: 68
        }
      ],
      bookItem: []
    };
  },
  methods: {
    addToBookList() {
      this.book.name = this.$refs.name.value;
      this.book.price = this.$refs.price.value;
      this.book.id = this.bookList.length + 1; 
      console.log(this.book.id);
      this.bookList.push({
        ...this.book
      });
      this.$refs.name.value = "";
      this.$refs.price.value = null;
    },
    addBookToCar(index) {
      let item = this.bookList[index];
      let isHasBook = this.bookItem.find(i => i.id === item.id);
      if (isHasBook) {
        isHasBook.number += 1;
      } else {
        this.bookItem.push({
          ...item,
          number: 1,
          isActive: true,
          totalPrice: 0
        });
      }
    },
    add(index) {
      this.bookItem[index].number += 1;
    },
    minus(index) {
      let number = this.bookItem[index].number;
      console.log(number)
      if (number > 1) {
        this.bookItem[index].number --;
      } else {
        if (window.confirm("确定要删除吗？")) {
          this.bookItem.splice(index, 1);
        }
      }
    }
  }
};
</script>

<style>
#app h1 {
  text-align: center;
}
#app div {
  margin: 5px 0;
}
#app table tr td button {
  cursor: pointer;
}
</style>
